package com.itholmes.tomcat;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class MyResponse {
	
	private String resp_http_version = "HTTP/1.1";
	private String resp_code = "100";
	private Map<String,String> resp_header = new HashMap<String,String>();
	private String resp_body = "";
	private OutputStream out;
	
	public MyResponse(OutputStream out) {
		this.out = out;
	}
	
	public String getResp_http_version() {
		return resp_http_version;
	}

	public void setResp_http_version(String resp_http_version) {
		this.resp_http_version = resp_http_version;
	}

	public String getResp_code() {
		return resp_code;
	}

	public void setResp_code(String resp_code) {
		this.resp_code = resp_code;
	}

	public Map<String, String> getResp_header() {
		return resp_header;
	}

	public void setResp_header(Map<String, String> resp_header) {
		this.resp_header = resp_header;
	}

	public String getResp_body() {
		return resp_body;
	}

	public void setResp_body(String resp_body) {
		this.resp_body = resp_body;
	}

	public String notFoundMethod() {
		String resp_http = "HTTP/1.1 404\r\n" + 
							"Server: tomcat\r\n" + 
							"Date: Thu, 03 Mar 2022 02:35:47 GMT\r\n" + 
							"Content-Type: text/html;charset=utf-8\r\n" + 
							"Content-Language: zh-CN";
		return resp_http;
	}
	
	public void serverErrorMethod(Exception e) {
		try {
			this.resp_code = "500";
			this.resp_body = 	"<html>\r\n" + 
								"<head>\r\n" + 
								"    <title>服务器错误</title>\r\n" + 
								"</head>\r\n" + 
								"<body>\r\n" +
								"<p>"+
								e.toString()+
								"</p>"+
								"</body>\r\n" + 
								"</html>";
			//这里的长度必须要设置不然，会报错的！！！客户端不知道长度，无法知道读取多少东西。
			byte[] bytes = this.resp_body.getBytes();
			
			String resp_http = this.resp_http_version + "//s" + this.resp_code + "/r/n" +
							"Content-Type: text/html;charset=utf-8\r\n" + 
							"Content-Language: zh-CN\r\n"+
							"Content-Length: "+ bytes.length +
							"\r\n\r\n"+
							this.resp_body;
		
			this.out.write(resp_http.getBytes());
			out.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	
	public void getWrite(String resp_http) {
		try {
				this.resp_code = "200";
				
				//这里的长度必须要设置不然，会报错的！！！客户端不知道长度，无法知道读取多少东西。
				byte[] bytes = resp_http.getBytes();
				this.resp_body = resp_http;
				
				String response_http = this.resp_http_version + " " + this.resp_code + "\r\n" +
											"Server: tomcat\r\n" + 
											"Date: Thu, 03 Mar 2022 03:30:09 GMT\r\n" + 
											"Content-Type: text/html;charset=UTF-8\r\n" + 
											"Content-Language: zh-CN\r\n" + 
											"Content-Length: "+ bytes.length +
											"\r\n\r\n"+
											this.resp_body;
			this.out.write(response_http.getBytes());
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
